#include<stdio.h>
#include<stdlib.h> //exit
#include<unistd.h> //pipe fork close getpid
#include<sys/types.h>
#include<sys/wait.h>
#include<string.h>

void ChildWrite(int fd)
{
    int cnt = 10;
    char buffer[256];
    while(cnt--)
    {
        snprintf(buffer,sizeof(buffer)-1,"I'm child: %d , where is my father?!",getpid());
        write(fd,buffer,sizeof(buffer)-1);
        sleep(1);
    }
}

void FatherRead(int fd)
{
    char buffer[256];
    while(1)
    {
        int num = read(fd,buffer,sizeof(buffer)-1);
        if(num <= 0)
            break;
        buffer[num] = 0;
        printf("It's father here , you message have been received\n:%s\n",buffer);
        sleep(1);
    }
}

int main()
{
    int arr[2] = {0};
    int ret = pipe(arr);
    if(ret < 0)
    {
        perror("create pipe fail");
        exit(1);
    }
    int pid = fork();
    if(pid == 0) //child
    {
        close(arr[0]); //close read end
        ChildWrite(arr[1]);
        close(arr[1]);
    }
    else if (pid > 0)
    {
        close(arr[1]); //close write end
        FatherRead(arr[0]);
        close(arr[0]);
        int state = -1;
        waitpid(ret,NULL,0);
        (void)state;
    }
    else
    {
        perror("create child process fail");
        exit(1);
    }
    return 0;
}





// int main()
// {
//     int fd[2] = {0}; //0 读 1写
//     int r = pipe(fd);
    
//     //printf("%d , %d \n",my_pipe[0],my_pipe[1]);

//     int ret = fork();
//     if(ret == 0)
//     {
//         close(fd[0]);//关闭读端
//         const char* st = "爸爸,我是你儿子!!!";
//         int cnt = 5;
//         while(cnt--)
//         {
//             write(fd[1],st,strlen(st));
//             sleep(1);
//         }
//         close(fd[1]);
//     }
//     else
//     {
//         close(fd[1]);//关闭写端
//         char buffer[256];
//         while(1)
//         {
//             int size = read(fd[0],buffer,255);
//             if(size <= 0)
//                 break;
//             buffer[size] = 0;
//             printf("%s\n",buffer);
//             sleep(1);
//         }
//         close(fd[0]);
//         int wait_id = -1;
//     waitpid(ret,&wait_id,0);
//     }

//     return 0;
// }